package cn.xuyang520.tyim.sys.service.impl;

import cn.xuyang520.tyim.sys.domain.TySysRelationGroupAuthority;
import cn.xuyang520.tyim.sys.domain.TySysRelationGroupAuthorityRepository;
import cn.xuyang520.tyim.sys.service.TySysAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by admin on 2017/4/4.
 */
@Service("tySysAuthorityService")
public class TySysAuthorityServiceImpl implements TySysAuthorityService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    TySysRelationGroupAuthorityRepository tySysRelationGroupAuthorityRepository;

    @Override
    @Cacheable(value = "tyCache", key = "'auth:groupAuthoritys:' + #p0")
    public List<String> findAuthorityCodesByGroupCode(String groupId) {
        if (StringUtils.isEmpty(groupId))
            return new LinkedList<>();
        String sql = "SELECT\n" +
                "tb_authority_code\n" +
                "FROM\n" +
                "ty_sys_relation_group_authority \n" +
                "WHERE\n" +
                "tb_group_code = ?";
        System.out.println("查询用户组权限");
        return jdbcTemplate.queryForList(sql, String.class, groupId);
    }

    @Override
    @CacheEvict(value = "tyCache", key = "'auth:groupAuthoritys:' + #p0")
    public void setAuthorityCodeByGroupCode(String groupCode, String authorityCode, boolean add) {
        jdbcTemplate.update("DELETE FROM\n" +
                "ty_sys_relation_group_authority\n" +
                "WHERE \n" +
                "tb_group_code = ? \n" +
                "AND tb_authority_code = ?", groupCode, authorityCode);

        if (add) {
            TySysRelationGroupAuthority authority = new TySysRelationGroupAuthority();
            authority.setTbAuthorityCode(authorityCode);
            authority.setTbGroupCode(groupCode);
            tySysRelationGroupAuthorityRepository.save(authority);
        }

    }



}
